package cn.rkylin.oms.refund.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.export.IExport;
import cn.rkylin.oms.ectrade.dao.EcTradeDAOImpl;
import cn.rkylin.oms.refund.service.IRefundService;
import cn.rkylin.oms.refund.vo.EcRefundItemVO;
import cn.rkylin.oms.refund.vo.RefundVO;
import cn.rkylin.oms.refund.vo.SearchConditionVO;

/**
 * 
 * @author jinshen 2017/04/20
 *
 */
@Controller
@RequestMapping("/ecRefundManager")
public class EcRefundController extends ApolloController {

    private static final Log logger = LogFactory.getLog(EcRefundController.class);

    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectEcRefund"; // 分页语句Statement名称

    @Autowired
    public ApolloService commonService;

    @Autowired
    public IRefundService ecRefundService;

    @Override
    public void afterPropertiesSet() throws Exception {
        setExportService((IExport) ecRefundService);
    }

    /**
     * 构造函数
     */
    public EcRefundController() {

    }

//    /**
//     * 待处理
//     * 
//     * @param quickSearch
//     *            快速查询条件
//     * @param formJson
//     *            高级检索条件
//     * @Param start 第几页
//     * @Param length 每页多少行
//     * @return 返回值JSON格式字符串
//     * @throws Exception
//     */
//    @ResponseBody
//    @RequestMapping(value = "/ecRefundNoDealList")
//    public Map<String, Object> ecTradeNoDealList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
//            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
//        // 查询条件
//        RefundVO param = new RefundVO();
//        param.setSplitStatus("n");
//        return getEcRefundList(quickSearch, start, length, formJson, param);
//    }
//
//    /**
//     * 待卖家处理
//     * 
//     * @param quickSearch
//     *            快速查询条件
//     * @param formJson
//     *            高级检索条件
//     * @Param start 第几页
//     * @Param length 每页多少行
//     * @return 返回值JSON格式字符串
//     * @throws Exception
//     */
//    @ResponseBody
//    @RequestMapping(value = "/ecRefundWaitSellerList")
//    public Map<String, Object> ecRefundWaitSellerList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
//            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
//        // 查询条件
//        RefundVO param = new RefundVO();
//        param.setSplitStatus("y");
//        param.setRefundStatus("WAITSELLER");
//        return getEcRefundList(quickSearch, start, length, formJson, param);
//    }
//
//    /**
//     * 待卖家处理
//     * 
//     * @param quickSearch
//     *            快速查询条件
//     * @param formJson
//     *            高级检索条件
//     * @Param start 第几页
//     * @Param length 每页多少行
//     * @return 返回值JSON格式字符串
//     * @throws Exception
//     */
//    @ResponseBody
//    @RequestMapping(value = "/ecRefundWaitBuyerList")
//    public Map<String, Object> ecRefundWaitBuyerList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
//            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
//        // 查询条件
//        RefundVO param = new RefundVO();
//        param.setSplitStatus("y");
//        param.setRefundStatus("WAITBUYER");
//        return getEcRefundList(quickSearch, start, length, formJson, param);
//    }

  /**
  * 等待卖家同意 列表
  * 
  * @param quickSearch
  *            快速查询条件
  * @param formJson
  *            高级检索条件
  * @Param start 第几页
  * @Param length 每页多少行
  * @return 返回值JSON格式字符串
  * @throws Exception
  */
 @ResponseBody
 @RequestMapping(value = "/ecRefundSellerAgreeList")
 public Map<String, Object> ecRefundSellerAgreeList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
         @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
     // 查询条件
     RefundVO param = new RefundVO();
     param.setRefundStatus("EC_WAIT_SELLER_AGREE");
     return getEcRefundList(quickSearch, start, length, formJson, param);
 }
    
 /**
 * 等待买家退货 列表
 * 
 * @param quickSearch
 *            快速查询条件
 * @param formJson
 *            高级检索条件
 * @Param start 第几页
 * @Param length 每页多少行
 * @return 返回值JSON格式字符串
 * @throws Exception
 */
@ResponseBody
@RequestMapping(value = "/ecRefundBuyerSendList")
public Map<String, Object> ecRefundBuyerSendList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
        @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
    // 查询条件
    RefundVO param = new RefundVO();
    param.setRefundStatus("EC_WAIT_BUYER_RETURN_GOODS");
    return getEcRefundList(quickSearch, start, length, formJson, param);
}

/**
 * 等待卖家确认收货 列表
 * 
 * @param quickSearch
 *            快速查询条件
 * @param formJson
 *            高级检索条件
 * @Param start 第几页
 * @Param length 每页多少行
 * @return 返回值JSON格式字符串
 * @throws Exception
 */
@ResponseBody
@RequestMapping(value = "/ecRefundSellerReciveList")
public Map<String, Object> ecRefundSellerReciveList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
        @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
    // 查询条件
    RefundVO param = new RefundVO();
    param.setRefundStatus("EC_WAIT_SELLER_CONFIRM_GOODS");
    return getEcRefundList(quickSearch, start, length, formJson, param);
}

/**
 * 卖家拒绝退款 列表
 * 
 * @param quickSearch
 *            快速查询条件
 * @param formJson
 *            高级检索条件
 * @Param start 第几页
 * @Param length 每页多少行
 * @return 返回值JSON格式字符串
 * @throws Exception
 */
@ResponseBody
@RequestMapping(value = "/ecRefundSellerRejectList")
public Map<String, Object> ecRefundSellerRejectList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
        @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
    // 查询条件
    RefundVO param = new RefundVO();
    param.setRefundStatus("EC_SELLER_REFUSE_BUYER");
    return getEcRefundList(quickSearch, start, length, formJson, param);
}
    /**
     * 完成
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @Param start 第几页
     * @Param length 每页多少行
     * @return 返回值JSON格式字符串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/ecRefundOverList")
    public Map<String, Object> ecRefundOverList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        // 查询条件
        RefundVO param = new RefundVO();
        param.setSplitStatus("y");
        param.setRefundStatus("OVER");
        return getEcRefundList(quickSearch, start, length, formJson, param);
    }

    /**
     * 取消
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @Param start 第几页
     * @Param length 每页多少行
     * @return 返回值JSON格式字符串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/ecRefundCanceledList")
    public Map<String, Object> ecRefundCanceledList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        // 查询条件
        RefundVO param = new RefundVO();
        param.setSplitStatus("y");
        param.setRefundStatus("CANCELED");
        return getEcRefundList(quickSearch, start, length, formJson, param);
    }

    /**
     * 根据不同的需求返回列表数据
     * 
     * @param quickSearch
     * @param start
     * @param length
     * @param formJson
     * @param type
     * @return
     */
    private Map<String, Object> getEcRefundList(String quickSearch, int start, int length, String formJson, RefundVO param) {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {

            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            // 设置项目id
            param.setPrjId(projectId);

            // 快速查询
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            quickSearch = quickSearch.trim();
            if (StringUtils.isNotBlank(quickSearch)) {
                param.setSearchCondition(quickSearch);
            }

            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            // json转换成为ＶＯ
            SearchConditionVO searchConditionVO = JSONObject.parseObject(formJson, SearchConditionVO.class);
            if (searchConditionVO != null) {
                // 项目
                if (StringUtils.isNotBlank(searchConditionVO.getPrjId())) {
                    param.setPrjId(searchConditionVO.getPrjId());
                }
                // 店铺
                if (StringUtils.isNotBlank(searchConditionVO.getShopId())) {
                    param.setShopId(searchConditionVO.getShopId());
                }
                // 平台
                if (StringUtils.isNotBlank(searchConditionVO.getShopType())) {
                    param.setShopType(searchConditionVO.getShopType());
                }
                // 平台交易码
                if (StringUtils.isNotBlank(searchConditionVO.getEcTradeCode())) {
                    param.setEcTradeCode(searchConditionVO.getEcTradeCode());
                }
                // 顾客编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcCustCode())) {
                    param.setBuyerNick(searchConditionVO.getEcCustCode());
                }
                // 平台商品编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcItemCode())) {
                    param.setEcItemCode(searchConditionVO.getEcItemCode());
                }
                // 平台规格编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcSkuCode())) {
                    param.setEcSkuCode(searchConditionVO.getEcSkuCode());
                }
                // 超时开始时间
                if (StringUtils.isNotBlank(searchConditionVO.getDateStart())) {
                    param.setDateStart(searchConditionVO.getDateStart());
                }
                // 超时结束时间
                if (StringUtils.isNotBlank(searchConditionVO.getDateEnd())) {
                    param.setDateEnd(searchConditionVO.getDateEnd());
                }
                // 退款原因
                if (StringUtils.isNotBlank(searchConditionVO.getRefundReason())) {
                    param.setRefundReason(searchConditionVO.getRefundReason());
                }
                // 退款状态
                if (StringUtils.isNotBlank(searchConditionVO.getRefundStatus())) {
                    param.setRefundStatus(searchConditionVO.getRefundStatus());
                }
                // 退款阶段
                if (StringUtils.isNotBlank(searchConditionVO.getRefundPhase())) {
                    param.setRefundPhase(searchConditionVO.getRefundPhase());
                }
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
//            replaceFieldsMap.put("exceptionType", "refund.errDesc");
            replaceFieldsMap.put("outTimeshow", "refund.refundTimeout");
            replaceFieldsMap.put("refundStatusNm", "refund.refundStatus");
            replaceFieldsMap.put("refundTradeStatus", "refund.ecTradeStus");

            // 排序语句生成
            String orderStatement = getOrderString(EcTradeDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 获取分页数据
            PageInfo<RefundVO> ecRefundVOList = ecRefundService.findByWhere(page, length, param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, ecRefundVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, ecRefundVOList.getTotal());
            returnMap.put(RETURN_DATA, ecRefundVOList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            ex.printStackTrace();
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 取得tab页面头上的记录数
     * 
     * @param quickSearch
     * @param start
     * @param length
     * @param formJson
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getTabCounts")
    public Map<String, Object> getTabCounts(String quickSearch, @RequestBody SearchConditionVO searchConditionVO) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 查询条件
            RefundVO param = new RefundVO();

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            // 设置项目id
            param.setPrjId(projectId);

            // 快速查询
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            quickSearch = quickSearch.trim();
            if (StringUtils.isNotBlank(quickSearch)) {
                param.setSearchCondition(quickSearch);
            }

            // // 高级查询检索条件
            // formJson = URLDecoder.decode(formJson, "UTF-8");
            // //json转换成为ＶＯ
            // SearchConditionVO searchConditionVO =
            // JSONObject.parseObject(formJson, SearchConditionVO.class);
            if (searchConditionVO != null) {
                // 项目
                if (StringUtils.isNotBlank(searchConditionVO.getPrjId())) {
                    param.setPrjId(searchConditionVO.getPrjId());
                }
                // 店铺
                if (StringUtils.isNotBlank(searchConditionVO.getShopId())) {
                    param.setShopId(searchConditionVO.getShopId());
                }
                // 平台
                if (StringUtils.isNotBlank(searchConditionVO.getShopType())) {
                    param.setShopType(searchConditionVO.getShopType());
                }
                // 平台交易码
                if (StringUtils.isNotBlank(searchConditionVO.getEcTradeCode())) {
                    param.setEcTradeCode(searchConditionVO.getEcTradeCode());
                }
                // 顾客编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcCustCode())) {
                    param.setBuyerNick(searchConditionVO.getEcCustCode());
                }
                // 平台商品编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcItemCode())) {
                    param.setEcItemCode(searchConditionVO.getEcItemCode());
                }
                // 平台规格编码
                if (StringUtils.isNotBlank(searchConditionVO.getEcSkuCode())) {
                    param.setEcSkuCode(searchConditionVO.getEcSkuCode());
                }
                // 超时开始时间
                if (StringUtils.isNotBlank(searchConditionVO.getDateStart())) {
                    param.setDateStart(searchConditionVO.getDateStart());
                }
                // 超时结束时间
                if (StringUtils.isNotBlank(searchConditionVO.getDateEnd())) {
                    param.setDateEnd(searchConditionVO.getDateEnd());
                }
                // 退款原因
                if (StringUtils.isNotBlank(searchConditionVO.getRefundReason())) {
                    param.setRefundReason(searchConditionVO.getRefundReason());
                }
                // 退款状态
                if (StringUtils.isNotBlank(searchConditionVO.getRefundStatus())) {
                    param.setRefundStatus(searchConditionVO.getRefundStatus());
                }
                // 退款阶段
                if (StringUtils.isNotBlank(searchConditionVO.getRefundPhase())) {
                    param.setRefundPhase(searchConditionVO.getRefundPhase());
                }
            }
            List<RefundVO> list = ecRefundService.findCounts(param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
//            int countWait = 0; // 待处理
//            int countWaitForBuyer = 0; // 待卖家操作
//            int countWaitForSeller = 0; // 待买家操作
            int countWaitAgree = 0;
            int countWaitSend = 0;
            int countWaitRecive = 0;
            int countWaitReject = 0;
            int countOver = 0; // 退款完成
            int countCancel = 0; // 退款关闭

            if (list != null && list.size() > 0) {
//                countWait = list.get(0).getCountWait() != null ? list.get(0).getCountWait().intValue() : 0;
//                countWaitForBuyer = list.get(0).getCountWaitForBuyer() != null ? list.get(0).getCountWaitForBuyer().intValue() : 0;
//                countWaitForSeller = list.get(0).getCountWaitForSeller() != null ? list.get(0).getCountWaitForSeller().intValue() : 0;
                countWaitAgree = list.get(0).getCountWaitAgree()!=null?list.get(0).getCountWaitAgree().intValue():0;
                countWaitSend = list.get(0).getCountWaitSend()!=null?list.get(0).getCountWaitSend().intValue():0;
                countWaitRecive = list.get(0).getCountWaitRecive()!=null?list.get(0).getCountWaitRecive().intValue():0;
                countWaitReject = list.get(0).getCountWaitReject()!=null?list.get(0).getCountWaitReject().intValue():0;
                countOver = list.get(0).getCountOver() != null ? list.get(0).getCountOver().intValue() : 0;
                countCancel = list.get(0).getCountCancel() != null ? list.get(0).getCountCancel().intValue() : 0;
            }
//            returnMap.put("countWait", countWait);
//            returnMap.put("countWaitForBuyer", countWaitForBuyer);
//            returnMap.put("countWaitForSeller", countWaitForSeller);
            returnMap.put("countAgree", countWaitAgree);
            returnMap.put("countSend", countWaitSend);
            returnMap.put("countRecive", countWaitRecive);
            returnMap.put("countReject", countWaitReject);
            
            returnMap.put("countOver", countOver);
            returnMap.put("countCancel", countCancel);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 取得订单商品列表
     * 
     * @param ecTradeId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/ecRefundOrderList")
    public Map<String, Object> getEcRefundOrderList(String ecRefundId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 查询条件
            EcRefundItemVO param = new EcRefundItemVO();

            if (StringUtils.isBlank(ecRefundId)) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "订单ID为空");
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("refundStatus", "refund.refundStatus");

            // 排序语句生成
            String orderStatement = getOrderString(EcTradeDAOImpl.class.getName(), "pageSelectEcRefundItem", replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            param.setEcRefundId(ecRefundId);

            PageInfo<EcRefundItemVO> ecRefundItemVOList = ecRefundService.findByWhere(1, Integer.MAX_VALUE, param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, ecRefundItemVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, ecRefundItemVOList.getTotal());
            returnMap.put(RETURN_DATA, ecRefundItemVOList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }
}
